#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017-09-29 17:28:40
# @Author  : WUQINGLONG
# @Contact : 1603763721@qq.com

# =======================================
# 优美胜于丑陋（Python 以编写优美的代码为目标）
# 明了胜于晦涩（优美的代码应当是明了的，命名规范，风格相似）
# 简洁胜于复杂（优美的代码应当是简洁的，不要有复杂的内部实现）
# 复杂胜于凌乱（如果复杂不可避免，那代码间也不能有难懂的关系，要保持接口简洁）
# 扁平胜于嵌套（优美的代码应当是扁平的，不能有太多的嵌套）
# 间隔胜于紧凑（优美的代码有适当的间隔，不要奢望一行代码解决问题）
# 可读性很重要（优美的代码是可读的）
# =======================================

"""
功能描述：
    1.学习使用lock
"""

from atexit import register
from random import randrange
from threading import Thread, currentThread, Lock
from time import sleep, ctime


class CleanOutputSet(set):
    def __str__(self):
        return ', '.join(x for x in self)


loops = (randrange(2, 5) for x in range(randrange(3, 7)))
remaining = CleanOutputSet()
lock = Lock()


def loop(seconds):
    name = currentThread().name
    lock.acquire()
    remaining.add(name)
    print('[%s] Started %s' % (ctime(), name))
    lock.release()
    sleep(seconds)
    lock.acquire()
    remaining.remove(name)
    print('[%s] Completed %s (%d secs)' % (ctime(), name, seconds))
    print('(remaining: %s)' % (remaining or 'None'))
    lock.release()


def _loop(seconds):
    name = currentThread().name
    with lock:
        remaining.add(name)
        print('[{0}] Started {1}'.format(ctime(), name))
    sleep(seconds)
    with lock:
        remaining.remove(name)
        print('[{0}] Completed {1} ({2} secs)'.format(ctime(), name, seconds))
        print('(remaining: {0})'.format(remaining or 'None'))


def main():
    for pause in loops:
        Thread(target=_loop, args=(pause,)).start()


@register
def _atexit():
    print('all DONE at: ', ctime())


if __name__ == '__main__':
    main()
